/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package com.cxhd.lis.ws.handle;

import com.google.gson.Gson;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.URL;
import java.net.URLConnection;

import java.util.concurrent.BlockingQueue;

/**
 *
 * @author Administrator
 */
public class MsgService extends Thread {

    Gson gson = new Gson();
    private BlockingQueue sendMessageQueue;//发送消息的队列
    private StartServer mws;

    private Message msg;
    private boolean flag = true;

    public MsgService(StartServer mws) {
        this.mws = mws;
        sendMessageQueue = mws.getSendQueue();
    }

    @Override
    public void run() {
        System.out.println("启动发送消息线程---------");
        Gson gson = new Gson();
        while (isFlag()) {
            try {

                msg = (Message) mws.getSendQueue().take();
               System.out.println(msg.getType());
                if (msg.getType().equalsIgnoreCase("localXml")) {
                   // sendToAll(msg);
                    handlerMsg(msg);
                }
            } catch (Exception ex) {

            }
        }
        System.out.println("结束发送消息线程 ---------");
    }

    public void handlerMsg(Message msg) {
        System.out.println("发送xml:"+msg.getBody());
        try {
            
            xmlStr2("http://127.0.0.1:8080/openImages.php", msg.getBody());
        } catch (Exception e) {
            e.printStackTrace();
        }
        
    }

  

    /**
     * @return the flag
     */
    public boolean isFlag() {
        return flag;
    }

    /**
     * @param flag the flag to set
     */
    public void setFlag(boolean flag) {
        this.flag = flag;
    }
    
    String xmlStr2(String urlx, String file) {
        String result = "";
        try {
            URL url = new URL(urlx);
            URLConnection conn = url.openConnection();
            conn.setDoOutput(true);
            OutputStreamWriter wr = new OutputStreamWriter(conn.getOutputStream(), "UTF-8");
            wr.write(file);
            wr.flush();
            wr.close();
            // Get the response
            BufferedReader rd = new BufferedReader(new InputStreamReader(conn.getInputStream()));
            String line;
            while ((line = rd.readLine()) != null) {
                result += line;
            }
            rd.close();
            return result;
        } catch (Exception e) {
            System.out.print(e);
        }
        return result;
    }
}
